﻿using IBatisNet.DataMapper;
using Unity.Interception.PolicyInjection.Pipeline;

namespace NoteHelper.Business.IbatisImpl
{
    /// <summary>
    /// 事务拦截器，必须继承ICallHandler
    /// </summary>
    public class TransactionInterceptor : ICallHandler
    {
        private log4net.ILog logger;

        private ISqlMapper Mapper { get { return SqliteMapper.Instance(); } }
        public int Order { get; set; }

        public TransactionInterceptor(int order)
        {
            this.Order = order;
            logger = log4net.LogManager.GetLogger(this.GetType());
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var methodName = getNext().Method.Name;
            logger.DebugFormat("{0} 事务日志", methodName);
            var session = Mapper.IsSessionStarted ? Mapper.LocalSession : Mapper.BeginTransaction();
            if (!session.IsTransactionStart)
            {
                logger.DebugFormat("{0}开启事务", methodName);
                session.BeginTransaction();
                var result = getNext()(input, getNext);
                if (result.Exception == null)
                {
                    logger.DebugFormat("{0}提交事务", methodName);
                    session.CommitTransaction();
                    session.OpenConnection();
                }
                else
                {
                    logger.DebugFormat("{0}事务回滚", methodName);
                    session.RollBackTransaction();
                }
                return result;
            }
            else
            {
                var result = getNext()(input, getNext);
                if (result.Exception != null)
                {
                    logger.DebugFormat("{0}事务回滚", methodName);
                    session.RollBackTransaction();
                }
                return result;
            }
        }
    }
}
